// controllers/distributionController.js
const dao = require("../dao/distributionDao");

exports.getList = async (req, res) => {
  try {
    const rows = await dao.getAll();
    const result = await Promise.all(
      rows.map(async (d) => {
        const hist = await dao.getPayHistoryByDistributorId(d.id); // ✅ 改这里
        return {
          id: d.id,
          type: d.type,
          name: d.name,
          phone: d.phone,
          withdrawInfo: {
            receiver: d.receiver,
            account: d.account,
            bank: d.bank,
          },
          totalAmount: Number(d.total_amount), // ✅ 转数字
          pendingAmount: Number(d.pending_amount),
          paidAmount: Number(d.paid_amount),
          status: d.status,
          payHistory: hist.map((h) => ({
            id: h.id,
            amount: Number(h.amount), // ✅ pay_history 的金额也转数字
            time: h.time,
            remark: h.remark || "",
          })),
        };
      })
    );
    res.json(result);
  } catch (error) {
    console.error("getList error:", error);
    res.status(500).json({ message: "获取分销主体失败" });
  }
};

exports.markPayout = async (req, res) => {
  const id = parseInt(req.params.id);
  try {
    const distributor = await dao.getById(id);
    if (!distributor) {
      return res.status(404).json({ message: "分销主体不存在" });
    }

    const pendingAmount = distributor.pending_amount;
    if (pendingAmount <= 0) {
      return res.json(true);
    }

    await dao.updatePayout(id, pendingAmount);
    await dao.insertPayHistory(id, pendingAmount);

    res.json(true);
  } catch (error) {
    console.error("markPayout error:", error);
    res.status(500).json(false);
  }
};
